package cn.pomelo.secondskill.controller;

import cn.pomelo.secondskill.common.AjaxResult;
import cn.pomelo.secondskill.exception.SecondsKillException;
import cn.pomelo.secondskill.model.Orders;
import cn.pomelo.secondskill.model.OrdersDetail;
import cn.pomelo.secondskill.service.RedisService;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

@RestController
@RequestMapping("/seconds")
public class SecondsController {

    @Resource
    RedisService redisService;

    /**
     * 秒杀付款
     *
     * @return 秒杀是否成功信息
     */
    @RequestMapping("/kill")
    public AjaxResult kill(@RequestBody Orders orders) {
        try {
            System.out.println(orders);
            OrdersDetail ordersDetail = redisService.secondsKill(orders);
            return AjaxResult.success(ordersDetail);
        } catch (SecondsKillException e) {
            return AjaxResult.failure(e.getMessage());
        }
    }

    @RequestMapping("/info")
    public AjaxResult secInfo(Integer userid, String orderId) {
        OrdersDetail ordersDetail = redisService.scOrderInfo(userid, orderId);
        return ordersDetail == null ? AjaxResult.failure("查询失败") : AjaxResult.success(ordersDetail);
    }

    @RequestMapping("/generate")
    public AjaxResult generate(Integer userid, Integer goodsId) {
        try {
            Orders detail = redisService.generate(userid, goodsId);
            return detail == null? AjaxResult.failure() : AjaxResult.success(detail);
        } catch (SecondsKillException e) {
            return AjaxResult.failure(e.getMessage());
        }

    }

}
